package com.mmlc.meimei.lichengkongjian.home;

import android.content.Intent;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.KeyEvent;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.ScrollView;
import android.widget.TextView;

import com.androidnetframe.httputil.BaseRequestFilterLayer;
import com.androidnetframe.httputil.EntryPageName;
import com.androidnetframe.requestbean.GlobalRequestBean;
import com.androidnetframe.responsejavabean.RequestError;
import com.google.gson.Gson;
import com.mmlc.inter.InterActivity;
import com.mmlc.meimei.lichengkongjian.Adapter.SearchHintAdapter;
import com.mmlc.meimei.lichengkongjian.R;
import com.mmlc.meimei.lichengkongjian.brand.BrandInfoActivity;
import com.mmlc.network.filter.SearchHintRequestFilter;
import com.mmlc.network.responsebean.SearchHintResult;
import com.mmlc.utils.FileUtils;
import com.mmlc.utils.KeyBoardUtils;
import com.mmlc.utils.ViewUtils;
import com.mmlc.utils.XUtils;
import com.mmlc.widget.MyGridView;
import com.mmlc.widget.MyListView;

import org.json.JSONException;
import org.json.JSONObject;
import org.xutils.common.Callback;

import java.util.ArrayList;

public class SearchActivity extends InterActivity {

    private ArrayList<String> search_history = new ArrayList<>();

    @Override
    protected int initContentView() {
        return R.layout.activity_search;
    }

    EditText edt_search;
    LinearLayout ll_search_hot, ll_search_result;
    RelativeLayout rl_search_history;
    MyGridView grid_hot, grid_history;
    //ListView list_result;
    ScrollView sv_hint;

    MyListView mlv_brand, mlv_classify;

    ArrayList<String> hotDatas, historyDatas;
    //ArrayList<GoodsListResponseBean.DataBean> results;
    SearchItemAdapter hotAdapter, historyAdapter;

    SearchHintAdapter<SearchHintResult.DataBean.CategoryBean> categoryAdapter;

    SearchHintAdapter<SearchHintResult.DataBean.BrandBean> brandAdapter;

    @Override
    protected void initView() {
        edt_search = ViewUtils.getView(activity, R.id.edt_search);
        edt_search.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                if (TextUtils.isEmpty(s.toString())) {
                    sv_hint.setVisibility(View.GONE);
                } else {
                    getSearchHint(s.toString());
                    sv_hint.setVisibility(View.VISIBLE);
                }
            }
        });

        ll_search_hot = ViewUtils.getView(activity, R.id.ll_search_hot);
        rl_search_history = ViewUtils.getView(activity, R.id.rl_search_history);
        grid_hot = ViewUtils.getView(activity, R.id.grid_search_hot);
        grid_history = ViewUtils.getView(activity, R.id.grid_search_history);

        categoryAdapter = new SearchHintAdapter<SearchHintResult.DataBean.CategoryBean>(this);
        brandAdapter = new SearchHintAdapter<SearchHintResult.DataBean.BrandBean>(this);
        sv_hint = ViewUtils.getView(activity, R.id.search_hint_sv);
        mlv_brand = ViewUtils.getView(activity, R.id.list_search_brand);
        mlv_brand.setAdapter(brandAdapter);
        mlv_brand.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                toSearch("brand_id",brandAdapter.getList().get(position).getId()
                        ,brandAdapter.getList().get(position).getBrand_name());
            }
        });
        mlv_classify = ViewUtils.getView(activity, R.id.list_search_classify);
        mlv_classify.setAdapter(categoryAdapter);
        mlv_classify.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                toSearch("cate_id",categoryAdapter.getList().get(position).getId()
                        ,categoryAdapter.getList().get(position).getName());
            }
        });


        //list_result = ViewUtils.getView(activity, R.id.list_result);

        hotDatas = new ArrayList<>();
        hotAdapter = new SearchItemAdapter(context, hotDatas);
        grid_hot.setAdapter(hotAdapter);
        historyDatas = new ArrayList<>();
        historyAdapter = new SearchItemAdapter(context, historyDatas);
        grid_history.setAdapter(historyAdapter);
//        results = new ArrayList<>();
//        resultAdapter = new ResultAdapter(context, results);
//        list_result.setAdapter(resultAdapter);
    }




    private void getSearchHint(final String keywords) {
        SearchHintRequestFilter filter = new SearchHintRequestFilter(this);
        filter.requestBean.keywords = keywords;
        filter.sendRequest(new BaseRequestFilterLayer.AccessResultFromFilter<SearchHintResult>() {
            @Override
            public void onSuccess(SearchHintResult result) {
                String x = new Gson().toJson(result);
                if (TextUtils.equals(keywords, edt_search.getText().toString())) {
                    categoryAdapter.getList().clear();
                    categoryAdapter.getList().addAll(result.getData().getCategory());
                    categoryAdapter.notifyDataSetChanged();
                    brandAdapter.getList().clear();
                    brandAdapter.getList().addAll(result.getData().getBrand());
                    brandAdapter.notifyDataSetChanged();
                }
            }

            @Override
            public void onFailed(View errorLayout, RequestError serverError, int failedType) {

            }
        });
    }




    @Override
    protected void onResume() {
        super.onResume();
        initDatas();
    }

    private void initDatas() {
        getHotDatas();
        getHistoryDatas();
    }

    private void getHotDatas() {
        if (EntryPageName.globalRequestBean != null && EntryPageName.globalRequestBean.getCode() == 0 && null!= EntryPageName.globalRequestBean.getData() ) {
            getHot(EntryPageName.globalRequestBean.getData());
        } else {
            JSONObject json = new JSONObject();
            try {
                json.put("nns_tag", "android_phone");
            } catch (JSONException e) {
                e.printStackTrace();
            }
            XUtils.httpPost(context, EntryPageName.globalRequest, json.toString(), new Callback.CommonCallback<String>() {
                @Override
                public void onSuccess(String result) {
                    if (!ViewUtils.isEmpty(result)) {
                        GlobalRequestBean global = new Gson().fromJson(result, GlobalRequestBean.class);
                        if (global.getCode() == 0) {
                            if(null!=global.getData())
                            getHot(global.getData());
                        }
                    }
                }

                @Override
                public void onError(Throwable ex, boolean isOnCallback) {
                    ll_search_hot.setVisibility(View.GONE);
                }

                @Override
                public void onCancelled(CancelledException cex) {
                    ll_search_hot.setVisibility(View.GONE);
                }

                @Override
                public void onFinished() {

                }
            });

        }
    }

    private void getHot(GlobalRequestBean.DataBean data) {
        hotDatas.clear();
        for (int i = 0; i < (data.getHot_words().size() > 9 ? 9 : data.getHot_words().size()); i++) {
            hotDatas.add(data.getHot_words().get(i));
        }
        hotAdapter.notifyDataSetChanged();

        if (hotDatas.size() == 0) {
            ll_search_hot.setVisibility(View.GONE);
        } else {
            ll_search_hot.setVisibility(View.VISIBLE);
        }
    }

    /**
     * 获取历史记录  文本读取
     */
    private void getHistoryDatas() {
        search_history = FileUtils.readStringFromFile("search_history", 9);
        if (search_history != null) {
            historyDatas.clear();
            historyDatas.addAll(search_history);
        }
        historyAdapter.notifyDataSetChanged();

        if (historyDatas.size() == 0) {
            rl_search_history.setVisibility(View.GONE);
        } else {
            rl_search_history.setVisibility(View.VISIBLE);
        }
    }

    @Override
    protected void initEvent() {
        ViewUtils.getView(activity, R.id.tv_cancel).setOnClickListener(this);
        ViewUtils.getView(activity, R.id.iv_history_delete).setOnClickListener(this);

//        edt_search.addTextChangedListener(new TextWatcher() {
//            @Override
//            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
//            }
//
//            @Override
//            public void onTextChanged(CharSequence s, int start, int before, int count) {
//                if (!ViewUtils.isEmpty(s.toString())) {
//                    vagueSearch(s.toString());
//                } else {
//                    rl_search_history.setVisibility(View.VISIBLE);
//                    ll_search_hot.setVisibility(View.VISIBLE);
//                    ll_search_result.setVisibility(View.GONE);
//                if (ViewUtils.isEmpty(s.toString()))
//                    initDatas();
//            }
//
//            @Override
//            public void afterTextChanged(Editable s) {
//            }
//        });

        edt_search.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                if (actionId == EditorInfo.IME_ACTION_SEARCH) {
                    KeyBoardUtils.closeKeybord(edt_search, context);
                    for (int i = 0; i < search_history.size(); i++) {
                        if (search_history.get(i).equals(edt_search.getText().toString()))
                            search_history.remove(i);
                    }
                    search_history.add(0, edt_search.getText().toString());
                    FileUtils.writeStringToFile("search_history", search_history);

                    startToSearch(edt_search.getText().toString());
//                    vagueSearch(edt_search.getText().toString());
                    return true;
                }
                return false;
            }
        });

        grid_hot.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                startToSearch(hotDatas.get(position));
//                accurateSearch(hotDatas.get(position));
            }
        });
        grid_history.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                startToSearch(historyDatas.get(position));
//                accurateSearch(historyDatas.get(position));
            }
        });
//        list_result.setOnItemClickListener(new AdapterView.OnItemClickListener() {
//            @Override
//            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
//                KeyBoardUtils.closeKeybord(edt_search, context);
//                for (int i = 0; i < search_history.size(); i++) {
//                    if (search_history.get(i).equals(edt_search.getText().toString()))
//                        search_history.remove(i);
//                }
//                search_history.add(0, edt_search.getText().toString());
//                FileUtils.writeStringToFile("search_history", search_history);
//
//                Intent intent = new Intent(activity, ProductInfoActivity.class);
//                intent.putExtra("name", results.get(position).getGoods_name()).putExtra("goods_id", results.get(position).getId());
//                startActivity(intent);
//            }
//        });
    }

    private void startToSearch(String s) {

        Intent intent = new Intent(activity, BrandInfoActivity.class);
        intent.putExtra("name", s)
                .putExtra("keywords", s);
        startActivity(intent);
    }

    private void toSearch(String key, String value, String name) {
        Intent intent = new Intent(activity, BrandInfoActivity.class);
        intent.putExtra("name", name)
                .putExtra(key, value);
        startActivity(intent);
    }

//    /**
//     * 精确查询
//     */
//    private void accurateSearch(String s) {
//        edt_search.setText(s);
//        vagueSearch(s);
//    }
//
//    /**
//     * 模糊查询
//     */
//    private void vagueSearch(String s) {
//        rl_search_history.setVisibility(View.GONE);
//        ll_search_hot.setVisibility(View.GONE);
//        ll_search_result.setVisibility(View.VISIBLE);
//
//        GoodsListRequestFilter filter = new GoodsListRequestFilter(activity);
//        filter.requestBean.keywords = s;
//        filter.sendRequest(new BaseRequestFilterLayer.AccessResultFromFilter<GoodsListResponseBean>() {
//            @Override
//            public void onSuccess(GoodsListResponseBean result) {
//                results.clear();
//                results.addAll(result.getData());
//                resultAdapter.notifyDataSetChanged();
//            }
//
//            @Override
//            public void onFailed(View errorLayout, RequestError serverError, int failedType) {
//            }
//        });
//    }

    @Override
    public void onClick(View v) {
        super.onClick(v);
        switch (v.getId()) {
            case R.id.tv_cancel:
                finish();
                break;
            case R.id.iv_history_delete:
                FileUtils.delete("search_history.txt");
                getHistoryDatas();
                break;
        }
    }
}
